package com.breakfast.fun.adapter.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.breakfast.fun.R;
import com.breakfast.fun.base.BaseListAdapter;
import com.breakfast.fun.common.CommonCart;
import com.breakfast.fun.dao.ProductCart;
import com.breakfast.fun.data.entity.home.Product;
import com.breakfast.fun.data.entity.home.Products;
import com.breakfast.fun.ui.home.product.SpecialDetailActivity;
import com.breakfast.fun.ui.home.product.SpecialProductActivity;
import com.breakfast.fun.util.DaoUtil;
import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

import static com.breakfast.fun.util.DaoUtil.getProductList;

/**
 * 逼格早餐适配器
 * Created by Administrator on 2016/9/7.
 */
public class SpecialProductAdapter extends BaseListAdapter<Product> {


    private List<ProductCart> productCarts;
    private CommonCart mCommonCart = new CommonCart();

    private boolean isClickAble = false;

    public SpecialProductAdapter(Context context, List<Product> list) {
        super(context, list);

        mCommonCart.init(context);

        productCarts = mCommonCart.productCartDao.loadAll();
        for (int i = 0; i < productCarts.size(); i++) {
            mCommonCart.totalPrice += productCarts.get(i).getTotalPrice();
            mCommonCart.totalNum += productCarts.get(i).getNum();
        }
        mCommonCart.event.setTotalPrice(mCommonCart.totalPrice);
        mCommonCart.event.setTotalNum(mCommonCart.totalNum);
        EventBus.getDefault().post(mCommonCart.event);
    }

    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_special_product, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Product data = getItem(i);
        imageUtil.loadUrlImage(data.getImage(), holder.mIvSpecialProduct);
        Glide.with(mContext)
                .load(data.getImage())
                .placeholder(R.drawable.bg_cache_banner)
                .error(R.drawable.bg_cache_banner)
                .crossFade()
                .into(holder.mIvSpecialProduct);

        List<ProductCart> productCarts = getProductList(data.getCategoryId(), data.getId(), SpecialProductActivity.chooseDate);
        if (productCarts != null && productCarts.size() == 1) {
            holder.mTvSpecialNum.setText(productCarts.get(0).getNum() + "");
        } else {
            holder.mTvSpecialNum.setText("0");
        }

        holder.mTvSpecialProductName.setText(data.getDes());
        holder.mTvSpecialPrice.setText("￥" + String.format("%.2f", data.getPrice()));

        //添加商品，逻辑和普通早餐一样（NormalProductAdapter）
        holder.mTvSpecialAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!isClickAble) {
                    return;
                }

                ProductCart productCart = new ProductCart(null, data.getCategoryId(), data.getId(), SpecialProductActivity.chooseDate);

                List<ProductCart> productCartList = getProductList(data.getCategoryId(), data.getId(), SpecialProductActivity.chooseDate);

                if (productCartList.size() == 0) {
                    productCart.setNum(1);
                    productCart.setImage(data.getImage());
                    productCart.setProductId(data.getId());
                    productCart.setName(data.getName());
                    productCart.setProductId(data.getId());
                    productCart.setPrice(data.getPrice());
                    productCart.setProductClassId(data.getProductClassId());
                    productCart.setTotalPrice(data.getPrice());
                    mCommonCart.productCartDao.insert(productCart);
                    holder.mTvSpecialNum.setText("1");
                } else {
                    productCartList.get(0).setNum(productCartList.get(0).getNum() + 1);
                    productCartList.get(0).setTotalPrice(productCartList.get(0).getPrice() * productCartList.get(0).getNum());
                    mCommonCart.productCartDao.update(productCartList.get(0));
                    holder.mTvSpecialNum.setText(productCartList.get(0).getNum() + "");
                }
                mCommonCart.totalNum += 1;
                mCommonCart.totalPrice += data.getPrice();
                mCommonCart.event.setTotalNum(mCommonCart.totalNum);
                mCommonCart.event.setTotalPrice(mCommonCart.totalPrice);
                EventBus.getDefault().post(mCommonCart.event);

            }
        });

        //删除商品，逻辑和普通早餐一样（NormalProductAdapter）
        holder.mTvSpecialDel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (holder.mTvSpecialNum.getText().equals("0")) {
                    return;
                }

                if (!isClickAble) {
                    return;
                }

                List<ProductCart> productCartList = DaoUtil.getProductList(data.getCategoryId(), data.getId(), SpecialProductActivity.chooseDate);
                productCartList.get(0).setNum(productCartList.get(0).getNum() - 1);
                mCommonCart.productCartDao.update(productCartList.get(0));
                holder.mTvSpecialNum.setText(productCartList.get(0).getNum() + "");
                if (holder.mTvSpecialNum.getText().equals("0")) {
                    mCommonCart.productCartDao.delete(productCartList.get(0));
                }
                mCommonCart.totalNum -= 1;
                mCommonCart.totalPrice -= data.getPrice();
                mCommonCart.event.setTotalNum(mCommonCart.totalNum);
                mCommonCart.event.setTotalPrice(mCommonCart.totalPrice);
                EventBus.getDefault().post(mCommonCart.event);
            }
        });

        //点击进入逼格详情页面
        holder.mIvSpecialProduct.setOnClickListener(v -> {
            if (!isClickAble) {
                return;
            }
            Intent intent = new Intent(mContext,
                    SpecialDetailActivity.class);
            Bundle bundle = new Bundle();
            Products products = new Products();
            products.setDate(SpecialProductActivity.chooseDate);
            products.setProduct(data);
            products.setCategoryId(data.getCategoryId());
            bundle.putSerializable("products", products);
            if (TextUtils.isEmpty(data.getClosetime())) {
                bundle.putString("closeTime", "22:00:00");
            } else {
                bundle.putString("closeTime", data.getClosetime());
            }
            intent.putExtras(bundle);
            mContext.startActivity(intent);
        });

        return convertView;
    }

    public boolean isClickAble() {
        return isClickAble;
    }

    public void setClickAble(boolean clickAble) {
        isClickAble = clickAble;
    }

    static class ViewHolder {
        @Bind(R.id.iv_special_product)
        ImageView mIvSpecialProduct;
        @Bind(R.id.tv_special_product_name)
        TextView mTvSpecialProductName;
        @Bind(R.id.tv_special_price)
        TextView mTvSpecialPrice;
        @Bind(R.id.tv_special_del)
        TextView mTvSpecialDel;
        @Bind(R.id.tv_special_num)
        TextView mTvSpecialNum;
        @Bind(R.id.tv_special_add)
        TextView mTvSpecialAdd;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
